package com.woman.beautylive.presentation.ui.main.me;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jakewharton.rxbinding.view.RxView;
import com.woman.beautylive.BeautyLiveApplication;
import com.woman.beautylive.R;
import com.woman.beautylive.data.bean.LoginInfo;
import com.woman.beautylive.data.bean.me.PlayBackInfo;
import com.woman.beautylive.data.bean.me.UserInfo;
import com.woman.beautylive.data.repository.SourceFactory;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.base.BaseActivity;
import com.woman.beautylive.presentation.ui.base.BaseFragment;
import com.woman.beautylive.presentation.ui.base.ptr.BasePtr;
import com.woman.beautylive.presentation.ui.chatting.DemoActivity;
import com.woman.beautylive.presentation.ui.chatting.utils.SharePreferenceManager;
import com.woman.beautylive.presentation.ui.login.LoginSelectActivity;
import com.woman.beautylive.presentation.ui.main.currency.CurrencyActivity;
import com.woman.beautylive.presentation.ui.main.me.profile.EditProfileActivity;
import com.woman.beautylive.presentation.ui.main.me.sublist.SubListActivity;
import com.woman.beautylive.presentation.ui.main.me.transaction.IncomeActivity;
import com.woman.beautylive.presentation.ui.main.me.transaction.RechargeActivity;
import com.woman.beautylive.presentation.ui.main.search.SearchActivity;
import com.woman.beautylive.presentation.ui.main.setting.SettingActivity;
import com.woman.beautylive.presentation.ui.main.webview.SimpleWebViewActivity;
import com.woman.beautylive.util.Const;
import com.woman.beautylive.util.DownLoadUtil;
import com.woman.beautylive.util.FrescoUtil;
import com.woman.beautylive.util.L;
import com.woman.beautylive.util.LocaleFormats;
import com.woman.beautylive.util.PicUtil;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.api.BasicCallback;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import rx.functions.Action1;

/**
 * 个人中心。
 *
 * @author huanzhang
 * @since 1.0.0
 */
public class MeFragment extends BaseFragment implements IMe {

    private static final int CODE_EDIT_PROFILE = 0x1001;
    private static final int CODE_EDIT_AVATER = 1200;

    private UserInfo mUserInfo;

    private PtrFrameLayout mPtr;
    private ImageButton mBack, mMsg;
    private TextView mOnline;
    //                            等级      送出的秀碧
    private TextView mName, mId, mSent;
    private ImageView mlevel,mChat;
    private SimpleDraweeView mPhoto ;
    private ImageView mSex, mEdit, mLevelImg;
//              收益    等级   我的钻石  设置     认证                  贡献
    private View mGet, mLevel, mDiamonds, mSetting,mAuthentication,mContribution;
    private TextView mplay_back_number,muser_level,muser_get,muser_money;
    private TextView mGetTv, mLevelTv, mDiamondsTv, mSettingTv,mAuthenticationTv,mContributionTv;
    private TextView mGetTip, mLevelTip, mDiamondsTip, mSettingTip,mAuthenticationTip,mContributionTip;
//     关注 粉丝
    private TextView mStar, mFans;
    private TextView mRank;
    private TextView mSign;
//    退出登录
    private TextView mLogout;
//    2016年7月15日01:17:32 这个方法的loadUserInfo 请求参数从null 改为了 Integer.parseInt(LocalDataManager.getInstance().getLoginInfo().getUserId())
    private MePresenter mePresenter;
//    回播item
    private LinearLayout item_playback,item_level,item_get,item_money;
//    使用列表存放，方便遍历
    private List<SimpleDraweeView> topContributeDrawees;

    private final UIHandler mUIHandler = new UIHandler(this);
    private static final int UNREAD= 0x99999;
    private static final int READ= 0x99998;
    private TextView newMsg;
    private List<Conversation> mDatas = new ArrayList<Conversation>();

    private Bitmap bitmap;
    private final static String ALBUM_PATH = Environment
            .getExternalStorageDirectory() + "/mypic_data/";

    public static MeFragment newInstance() {
        return new MeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_main_me;
    }

    @Override
    public void onResume() {
//        MobclickAgent.onPageStart("个人中心");
        super.onResume();
//        mPtr.autoRefresh();
        try{
            mDatas = JMessageClient.getConversationList();
            L.e("lw","收到消息"+mDatas);

            for (int i=0;i<mDatas.size();i++){
                Conversation conv=mDatas.get(i);
                if (conv.getUnReadMsgCnt()>0) {
                    newMsg.setVisibility(View.VISIBLE);
                    break;
                }else
                    newMsg.setVisibility(View.GONE);
            }
        }catch (NullPointerException e){
        }

        mePresenter.loadUserInfo(Integer.parseInt(LocalDataManager.getInstance().getLoginInfo().getUserId()));
    }

    @Override
    public void onPause() {
//        MobclickAgent.onPageEnd("个人中心");
        super.onPause();
    }
    @Override
    protected void initViews(View view) {
        newMsg = $(view, R.id.new_msg);

        mBack = (ImageButton) view.findViewById(R.id.imgbtn_toolbar_back);
        mOnline = (TextView) view.findViewById(R.id.me_massage);
        mPtr = (PtrFrameLayout)view.findViewById(R.id.fragment_me_ptr);
        mPhoto = $(view, R.id.my_me_photo);
        mChat = $(view, R.id.me_chat);

        mName = $(view, R.id.me_name);
        mlevel = $(view, R.id.me_level);
        mSent = $(view, R.id.me_send);
        mSex = $(view, R.id.me_sex);
        mEdit = $(view, R.id.me_edit);
        mId = $(view, R.id.me_id);
        BasePtr.setPagedPtrStyle(mPtr);
        mSign=$(view,R.id.me_sign);
        if (mSign!=null){
            mSign.setVisibility(View.GONE);
        }
        mPtr.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                Log.i("mrl",LocalDataManager.getInstance().getLoginInfo().getUserId()+"id"+LocalDataManager.getInstance().getLoginInfo().getToken());
                mePresenter.loadUserInfo(Integer.parseInt(LocalDataManager.getInstance().getLoginInfo().getUserId()));
            }
        });

        topContributeDrawees = new ArrayList<>();
        SimpleDraweeView draweeTop1 = $(view, R.id.me_coin_top1);
        SimpleDraweeView draweeTop2 = $(view, R.id.me_coin_top2);
        SimpleDraweeView draweeTop3 = $(view, R.id.me_coin_top3);
        topContributeDrawees.add(draweeTop1);
        topContributeDrawees.add(draweeTop2);
        topContributeDrawees.add(draweeTop3);

        mGet = $(view, R.id.fragment_me_item_myget);
        mGet.setVisibility(View.GONE);
        mLevel = $(view, R.id.fragment_me_item_level);
        mLevel.setVisibility(View.GONE);
        mDiamonds = $(view, R.id.fragment_me_item_diamonds);
        mDiamonds.setVisibility(View.GONE);
        mSetting = $(view, R.id.fragment_me_item_setting);
        mAuthentication=$(view, R.id.fragment_me_item_authentication);
        mContribution=$(view, R.id.fragment_me_item_contribution);

        mGetTv = $(mGet, R.id.item_me_txt);
        mLevelTv = $(mLevel, R.id.item_me_txt);
        mDiamondsTv = $(mDiamonds, R.id.item_me_txt);
        mSettingTv = $(mSetting, R.id.item_me_txt);
        mAuthenticationTv=$(mAuthentication, R.id.item_me_txt);
        mContributionTv=$(mContribution, R.id.item_me_txt);

        mGetTip = $(mGet, R.id.item_me_tip);
        mLevelTip = $(mLevel, R.id.item_me_tip);
        mDiamondsTip = $(mDiamonds, R.id.item_me_tip);
        mSettingTip = $(mSetting, R.id.item_me_tip);
        mAuthenticationTip=$(mAuthentication, R.id.item_me_tip);
        mContributionTip=$(mContribution, R.id.item_me_tip);

        muser_level=$(view,R.id.user_level);
        mplay_back_number=$(view,R.id.play_back_number);
        muser_get=$(view,R.id.user_get);
        muser_money=$(view,R.id.user_money);

        mStar = $(view, R.id.me_user_info_star);
        mFans = $(view, R.id.me_user_info_fans);

        mRank = $(view,R.id.me_coin_rank_tv);

        mLevelImg = $(mLevel, R.id.item_me_img);

        mLogout = $(view, R.id.fragment_me_logout);
        item_playback=$(view, R.id.item_playback);
        item_level=$(view,R.id.item_level);
        item_get=$(view,R.id.item_get);
        item_money=$(view,R.id.item_money);
        initData();

//        设置
        RxView.clicks(mSetting).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        startActivity(SettingActivity.createIntent(getActivity()));
                    }
                });

        RxView.clicks(mStar).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(SubListActivity.createIntent(getActivity(), mUserInfo.getId(), SubListActivity.KEY_STAR));
                        }
                    }
                });
        RxView.clicks(mFans).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(SubListActivity.createIntent(getActivity(), mUserInfo.getId(), SubListActivity.KEY_FANS));
                        }
                    }
                });
        RxView.clicks($(view, R.id.me_user_info_fans_tv)).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(SubListActivity.createIntent(getActivity(), mUserInfo.getId(), SubListActivity.KEY_FANS));
                        }
                    }
                });

        RxView.clicks($(view, R.id.me_user_info_star_tv)).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(SubListActivity.createIntent(getActivity(), mUserInfo.getId(), SubListActivity.KEY_STAR));
                        }
                    }
                });
//        老板的贡献榜
        RxView.clicks(mRank).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(CurrencyActivity.createIntent(getActivity(), mUserInfo.getId(), mUserInfo.getAnchorBalance()));
                        }
                    }
                });
//        回播记录
        RxView.clicks(item_playback).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(PlayBackListActivity.createIntent(getActivity(), mUserInfo));
                        }
                    }
                });
//                等级
        RxView.clicks(item_level).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Log.i("mrl",getString(R.string.me_level_description_url,mUserInfo.getId())+"这啥");
                        if (mUserInfo != null) {
                            startActivity(SimpleWebViewActivity.createIntent(getActivity(),SourceFactory.wrapPath(getString(R.string.me_level_description_url, mUserInfo.getId()))));
                        }
                    }
                });
//        收益
        RxView.clicks(item_get).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(IncomeActivity.createIntent(getActivity(),mUserInfo.getAvatar()));
                        }
                    }
                });
//        账户
        RxView.clicks(item_money).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(RechargeActivity.createIntent(getActivity()));
                        }
                    }
                });
//    左上角的搜索
        RxView.clicks($(view, R.id.sel_me_btn_serach)).throttleFirst(Const
                .VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        startActivity(SearchActivity.createIntent(getActivity()));
                        getActivity().overridePendingTransition(R.anim.fragment_slide_right_in, R
                                .anim.fragment_slide_right_out);
                    }
                });

        subscribeClick(mEdit, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (mUserInfo != null) {
                    startActivityForResult(EditProfileActivity.createIntent(getActivity(),
                            mUserInfo), CODE_EDIT_PROFILE);
                }
            }
        });

        subscribeClick(mDiamonds, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                startActivity(RechargeActivity.createIntent(getActivity()));
            }
        });

        subscribeClick(mGet, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (mUserInfo != null) {
                    startActivity(IncomeActivity.createIntent(getActivity(), mUserInfo.getAvatar()));
                }
            }
        });

        subscribeClick(mLevel, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (mUserInfo != null) {
                    startActivity(SimpleWebViewActivity.createIntent(getActivity(),
                            SourceFactory.wrapPath(getString(R.string.me_level_description_url, mUserInfo.getLevel()))));
                }
            }
        });

        subscribeClick(mPhoto, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (mUserInfo != null) {
                    startActivityForResult(EditProfileActivity.createIntent(getActivity(),
                            mUserInfo), CODE_EDIT_PROFILE);
                }
            }
        });
        subscribeClick(mlevel, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (mUserInfo != null) {
                    startActivityForResult(EditProfileActivity.createIntent(getActivity(),
                            mUserInfo), CODE_EDIT_PROFILE);
                }
            }
        });
        //      投票贡献榜
        subscribeClick(mContribution, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (mUserInfo != null) {
                    startActivity(CurrencyActivity.createIntent(getActivity(), mUserInfo.getId(), mUserInfo.getAnchorBalance()));
                }
            }
        });

//      认证
        subscribeClick(mAuthentication, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (mUserInfo != null) {
//                    startActivity(SimpleWebViewActivity.createIntent(getActivity(),
//                            SourceFactory.wrapPath(getString(R.string.me_authentication_url, mUserInfo.getId()))));
                    startActivity(AuthenticationActivity.createIntent(getActivity()));
                }
            }
        });
        //消息列表
        subscribeClick(mChat, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (mUserInfo != null) {
                    startActivity(DemoActivity.createIntent(getActivity()));
                    getActivity().overridePendingTransition(R.anim.fragment_slide_right_in, R
                            .anim.fragment_slide_right_out);
                }
            }
        });

    }

    private void initData() {
        mePresenter = new MePresenter(this);
        mBack.setVisibility(View.GONE);
        mGetTv.setText(getResources().getString(R.string.me_get));
        mLevelTv.setText(getResources().getString(R.string.me_level));
        mDiamondsTv.setText(getResources().getString(R.string.me_diamonds, getString(R.string.app_currency)));
        mSettingTv.setText(getResources().getString(R.string.me_setting));
        mAuthenticationTv.setText(getResources().getString(R.string.me_authentication));
        mContributionTv.setText(getResources().getString(R.string.me_contribution));
        mRank.setText(getString(R.string.coin_rank, getString(R.string.app_currency)));

        mSettingTip.setVisibility(View.GONE);
        mLevelTip.setVisibility(View.GONE);
        mLevelImg.setVisibility(View.VISIBLE);
        mAuthenticationTip.setVisibility(View.VISIBLE);
        mContributionTip.setVisibility(View.GONE);
        RxView.clicks(mLogout)
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        //Move these operation into LoginSelectActivity
//                        LocalDataManager.getInstance().clearLoginInfo();
//                        //Clear all third authorize
//                        new QQ(getActivity()).removeAccount(true);
//                        new Wechat(getActivity()).removeAccount(true);
//                        new SinaWeibo(getActivity()).removeAccount(true);

                        startActivity(LoginSelectActivity.createIntent(getActivity()));
                        ((BaseActivity) getActivity()).sendFinishBroadcast(LoginSelectActivity
                                .class.getSimpleName());
                    }
                });
    }

//    这里是用来给wsloginrequest 设置信息的，为了不进行一次网络请求，所以这里写了个全局。。。不要问我之前那里如何写的，我也不知道
    public static  UserInfo mrlinfo;
    @Override
    public void showInfo(UserInfo info) {
        mrlinfo=info;
        if (info == null) {
            return;
        }
        mUserInfo = info;
        if (info.getSnap() != null) {
            FrescoUtil.frescoResize(
                    SourceFactory.wrapPathToUri(info.getSnap()),
                    getWidth(this.getActivity()),
                    getWidth(this.getActivity()),
                    mPhoto
            );
        }
//            Const.MAIN_HOST_URL + mUserInfo.getSnap()
            new Thread(new Runnable() {

                @Override
                public void run() {
                    URL url;
                    try {
                        url = new URL(Const.MAIN_HOST_URL + mUserInfo.getSnap());
                        InputStream is = url.openStream();
                        bitmap = BitmapFactory.decodeStream(is);
                        saveFile(bitmap, "yangmi.jpg");
                        is.close();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        //TODO add min photo
        if (info.getNickname() != null) {
            mName.setText(info.getNickname());

            //IM的nickname
            String nickName = mName.getText().toString().trim();
            if (nickName != null && !nickName.equals("")) {
                cn.jpush.im.android.api.model.UserInfo myUserInfo = JMessageClient.getMyInfo();
                L.i("lw", "我的名字" + myUserInfo);
                try{
                    myUserInfo.setNickname(nickName);
                    JMessageClient.updateMyInfo(cn.jpush.im.android.api.model.UserInfo.Field.nickname, myUserInfo, new BasicCallback() {
                        @Override
                        public void gotResult(final int status, String desc) {
                            //更新跳转标志
                            SharePreferenceManager.setCachedFixProfileFlag(false);
                        }
                    });
                }catch (NullPointerException e){

                }
            }
        }
        mSex.setImageResource(info.getSex() == 0 ? R.drawable.ic_male : R.drawable.ic_female);

        if (info.getSex() ==0 || info.getSex()==1) {
            //IM的gender
                final cn.jpush.im.android.api.model.UserInfo myUserInfo = JMessageClient.getMyInfo();
                L.i("lw", "我的性别" + myUserInfo);
                try{
                    myUserInfo.setGender(info.getSex() == 0 ? cn.jpush.im.android.api.model.UserInfo.Gender.male : cn.jpush.im.android.api.model.UserInfo.Gender.female);
                    JMessageClient.updateMyInfo(cn.jpush.im.android.api.model.UserInfo.Field.gender, myUserInfo, new BasicCallback() {
                        @Override
                        public void gotResult(final int status, String desc) {
                            //更新跳转标志
                            L.e("lw", "我的性别" + status+"+"+desc+"+"+myUserInfo);
                            SharePreferenceManager.setCachedFixProfileFlag(false);
                        }
                    });
                }catch (NullPointerException e){
                }
        }

        if (info.getId() != null) {
            mId.setText(getResources().getString(R.string.me_id) + info.getId());
        }
        if (info.getLevel() != null) {
            mlevel.setImageResource(PicUtil.getLevelImageId(getActivity(),Integer.parseInt(info.getLevel())));

                //IM的level
                final cn.jpush.im.android.api.model.UserInfo myUserInfo = JMessageClient.getMyInfo();
                L.i("lw", "我的等级" + myUserInfo);
            String level=info.getLevel();
                try{
                    myUserInfo.setRegion(level);
                    JMessageClient.updateMyInfo(cn.jpush.im.android.api.model.UserInfo.Field.region, myUserInfo, new BasicCallback() {
                        @Override
                        public void gotResult(final int status, String desc) {
                            L.e("lw", "我的等级"+status+"+"+desc+"+"+ myUserInfo);
                            //更新跳转标志
                            SharePreferenceManager.setCachedFixProfileFlag(false);
                        }
                    });
                }catch (NullPointerException e){
                }
        }
        if (info.getTotalContribution() != 0) {
            mSent.setText("送出  " + info.getTotalContribution());
//            PicUtil.TextViewSpandImg(this.getActivity(), mSent, R.drawable
//                    .ic_me_myaccount_reddiamond);
        }

        //贡献榜前三的头像
        List<String> topAvatars = info.getTopContributeUsers();
        if (topAvatars!=null){
            int avatarSize = (int) getResources().getDimension(R.dimen.avatar_size_default);
            //取可显示的头像个数和返回的头像个数的较小值执行遍历
            for (int i=0; i< Math.min(topContributeDrawees.size(), topAvatars.size()); i++){
                FrescoUtil.frescoResize(SourceFactory.wrapPathToUri(topAvatars.get(i)),
                        avatarSize, avatarSize, topContributeDrawees.get(i));
            }
        }

        mStar.setText(getString(R.string.my_info_follower_count, info.getFolloweesCount()));
        mFans.setText(getString(R.string.my_info_followee_count, info.getFollowersCount()));
        if (info.getIntro()!=null) {
            mSign.setText(info.getIntro());
        }else {
            mSign.setText("当事人很懒,什么都没有留下,只留下一行空白");
        }

        mDiamondsTip.setText(LocaleFormats.formatMoney(getActivity(), info.getCoinBalance()));
        mGetTip.setText(LocaleFormats.formatMoney(getActivity(), info.getEarnbean()));
        mAuthenticationTip.setText("未认证");
        mAuthenticationTip.setTextColor(getResources().getColor(R.color.yunkacolor_h_1));

//        直播
        if (info.getPlayBackCount()!=null) {
            mplay_back_number.setText(info.getPlayBackCount() + "个");
        }

//        我的账户
        if (info.getCoinBalance()!=null) {
            muser_money.setText(LocaleFormats.formatMoney(getActivity(), DownLoadUtil.conversionNumber(Integer.parseInt(info.getCoinBalance())) + " "));
        }
        PicUtil.TextViewSpandImg(this.getActivity(), muser_money, R.drawable.ic_me_myaccount_reddiamond);

        if (info.getEarnbean()!=null) {
            muser_get.setText(LocaleFormats.formatMoney(getActivity(), DownLoadUtil.conversionNumber(Integer.parseInt(info.getEarnbean()))) + " 票");
        }
        if (info.getLevel()!=null) {
            muser_level.setText(LocaleFormats.formatMoney(getActivity(), info.getLevel()) + " 级");
        }
        // mLevelTip.setText(info.getLevel());
        //TODO setlevel icon
        Context context = this.getActivity();

        int resId = context.getResources().getIdentifier("rank_" + info.getLevel(), "drawable",
                context.getPackageName());
        mLevelImg.setImageResource(resId);
        savaMeInfo(info);
    }

    @Override
    public void getPlayLists(List<PlayBackInfo> playBackList) {

    }

    @Override
    public void getPlayUrl(String url) {

    }

    @Override
    public void getHitCode(int code) {

    }

    @Override
    public void getRemoveHitCode(int code) {

    }

    @Override
    public void getStartCode(int code) {

    }

    @Override
    public void getRemoveStartCode(int code) {

    }


    private void savaMeInfo(UserInfo info){
        LoginInfo loginInfo = LocalDataManager.getInstance().getLoginInfo();
        loginInfo.setLevel(info.getLevel());
        loginInfo.setAvatar(info.getAvatar());
        loginInfo.setCurrentRoomNum(info.getCurrentRoomNum());
        loginInfo.setNickname(info.getNickname());
        loginInfo.setTotalBalance(Long.parseLong(info.getCoinBalance()));
        LocalDataManager.getInstance().saveLoginInfo(loginInfo);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mePresenter.unsubscribeTasks();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_EDIT_PROFILE && resultCode == Activity.RESULT_OK) {
            if (mePresenter != null) {
                mePresenter.loadUserInfo(Integer.parseInt(LocalDataManager.getInstance().getLoginInfo().getUserId()));
            } else {
                L.e(LOG_TAG, "What, presenter is already null?");
            }
        }
        if(requestCode == CODE_EDIT_AVATER&& resultCode == Activity.RESULT_OK){
            Uri uri = data.getData();
            mPhoto.setImageURI(uri);
            L.e("lw","头像"+uri);
        }
    }
    @Override
    public void showLoadingComplete() {
        super.showLoadingComplete();
        mPtr.refreshComplete();
    }
    /**
     * 在会话列表中接收消息
     *
     * @param event 消息事件
     */
    public void onEvent(MessageEvent event) {
        Message msg = event.getMessage();
        Log.d("lw", "收到消息：msg = " + msg.toString());
        ConversationType convType = msg.getTargetType();
        if (convType == ConversationType.single){
            final cn.jpush.im.android.api.model.UserInfo userInfo = (cn.jpush.im.android.api.model.UserInfo) msg.getTargetInfo();
            final String targetID = userInfo.getUserName();
            final Conversation conv = JMessageClient.getSingleConversation(targetID, userInfo.getAppKey());
            L.e("lw","消息数"+conv.getUnReadMsgCnt());
            if (conv != null&&conv.getUnReadMsgCnt()>0) {
                mUIHandler.sendEmptyMessage(UNREAD);
            }
        }
    }

    private static class UIHandler extends Handler {
        private final WeakReference<MeFragment> mActivity;

        public UIHandler(MeFragment activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            MeFragment activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case UNREAD:
                        activity.newMsg.setVisibility(View.VISIBLE);
                        break;
                }
            }
        }
    }

    // 指定保存的路径：
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(ALBUM_PATH);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

        final File path=myCaptureFile;
        if (!path.equals("")&&path!=null){

            try{
                cn.jpush.im.android.api.model.UserInfo myInfo = JMessageClient.getMyInfo();
                BeautyLiveApplication.setPicturePath(myInfo.getAppKey());
                JMessageClient.updateUserAvatar(new File(String.valueOf(path)), new BasicCallback() {
                    @Override
                    public void gotResult(int status, final String desc) {
                        L.i("lw", "我的头像 失败" + path+status+desc);
                        if (status == 0) {
                            L.i("lw", "我的头像 " + path);
                        }
                    }
                });
            }catch (NullPointerException e){
            }
        }
    }
}
